<?php
class DefaultInstall3Action extends InstallAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'tpl';
		$this->layout = 'index';
	}

	public function execute()
	{
		$dbInfo				= C('LtConfig')->get('db.info');
		$dbInfo['prefix']	= C('LtConfig')->get('db.table.prefix');
		$this->data['db']	= $dbInfo;
		
		if($this->context->post('setdb')!='')
		{
			$host 			= $this->context->post('host');
			$username		= $this->context->post('username');
			$password 		= $this->context->post('password');
			$dbname 		= $this->context->post('dbname');
			$prefix 		= $this->context->post('prefix');
			
			foreach(array('host','username','password','dbname','prefix',) as $k)
			{
				$this->data['db'][$k]	= $$k;
			}
			
			if($host=='')
			{
				$this->data['err']	= '请填写数据库服务器';
				return;
			}
			
			if($dbname=='')
			{
				$this->data['err']	= '请填写数据库名';
				return;
			}
			
			if($prefix=='')
			{
				$this->data['err']	= '请填写表名前缀';
				return;
			}
			
			if(strstr($prefix, '.'))
			{
				$this->data['err']	= '请填写合法的表名前缀，不能带有.等特殊符号';
				return;
			}
			
			if(!@mysql_connect($host, $username, $password))
			{
				$this->data['err']	= '数据库连接出错，请检查你的配置';
				return;
			}
			else
			{
				mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname`");
				if(mysql_errno())
				{
					$this->data['err']	= '创建数据库出错:'.mysql_error();
					return;
				}
				mysql_close();
			}
			
			$singlehost = array("adapter" => "mysql", "host" => $host, "port"=>'', "username"=>$username, "password" => $password, "dbname" => $dbname, 'pconnect' => '');
			
			$confBaseDir	= substr(dirname(__FILE__), 0, strrpos(__FILE__, "app")).'conf/standard/';
			
			$fp 			= fopen($confBaseDir.'db.conf.php', 'r');
			$content 		= fread($fp, filesize($confBaseDir.'db.conf.php'));
			fclose($fp);
			
			$content 	= preg_replace('~\$singlehost = .*?;~is', "\$singlehost = array('adapter' => 'mysql', 'host' => '$host', 'port'=>'', 'username'=>'$username', 'password' => '$password', 'dbname' => '$dbname', 'pconnect' => '');", $content);
			$content 	= preg_replace('~\$config\["db\.table\.prefix"\] = .*?;~is', "\$config[\"db.table.prefix\"] = '$prefix';", $content);
			
			$fp 		= fopen($confBaseDir.'db.conf.php', 'w');
			fwrite($fp, trim($content));
			fclose($fp);
			
			$confBaseDir	= substr(dirname(__FILE__), 0, strrpos(__FILE__, "app")).'conf/';
			
			$configFile 	= $confBaseDir . 'conf_dev.php';
			if(!is_file($configFile))
			{
				$configFile 	= $confBaseDir . 'conf.php';
			}
			C('LtConfig')->loadConfigFile($configFile,true);
			
			header('Location:'.C('LtUrl')->generate('Default','Install4'));
		}
	}
}
